﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using ConsoleService.Helps;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MimeKit.Text;
using MimeKit;
using NETCore.MailKit.Core;
using NETCore.MailKit.Infrastructure.Internal;
using NLog;
using MailKit.Net.Smtp;
using System.IO;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;
using static Org.BouncyCastle.Math.EC.ECCurve;
using Microsoft.AspNetCore.Hosting;
using ConsoleService.Cache;
using Common;

namespace ConsoleService.Services
{
    public class EmailServices
    {
        private readonly IOptions<EmailOptions> _options;
        private readonly IEmailService _EmailService;
        private Logger logger = LogManager.GetCurrentClassLogger();
        public EmailServices(IEmailService emailService, IOptions<EmailOptions> options)
        {
            this._EmailService = emailService;
            this._options = options;
        }


        public bool SendEmail()
        {
            /*
             设置中开启服务：
             POP3/SMTP服务=》开启
             */
            try
            {
                //设置发送人的邮件地址和名称，在接收人接收到邮件提示时会显示该信息
                var text = $"测试邮件发送-{DateTime.Now.ToString()}";
                _EmailService.Send("1294833881@qq.com", "测试邮件", text, Encoding.UTF8, false); //465 端口
                Console.WriteLine("SendEmail 发送成功！");
                return true;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                Console.WriteLine("SendEmail 发送失败：" + ex.Message);
                return false;
            }

        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="model"></param>
        public void SendEmail(EmailModel model)
        {
            //https://blog.csdn.net/sD7O95O/article/details/127455997

            try
            {
                var config = _options.Value;
                var emailMessage = new MimeMessage();

                //邮件发件人默认系统配置
                emailMessage.From.Add(new MailboxAddress(config.SenderName, config.UserName));

                //邮件收件人
                model.To.ForEach(z =>
                {
                    emailMessage.To.Add(new MailboxAddress(z));
                });

                //邮件抄送人
                model.Cc.ForEach(z =>
                {
                    emailMessage.Cc.Add(new MailboxAddress(z));
                });

                //邮件主题
                emailMessage.Subject = model.Subject;

                var alternative = new Multipart("alternative");

                if (model.IsHtml)
                    alternative.Add(new TextPart("html") { Text = model.Context });
                else
                    alternative.Add(new TextPart("plain") { Text = model.Context });


                //附件列表 文件绝对路径
                if (model.Files != null && model.Files.Count > 0)
                {
                    model.Files.ForEach(f =>
                    {
                        if (File.Exists(f))
                        {
                            var attachment = new MimePart()//("image", "png")
                            {
                                Content = new MimeContent(File.OpenRead(f), ContentEncoding.Default),
                                //ContentObject = new ContentObject(File.OpenRead(f), ContentEncoding.Default),
                                ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
                                ContentTransferEncoding = ContentEncoding.Base64,
                                FileName = Path.GetFileName(f)
                            };
                            alternative.Add(attachment);
                        }
                    });
                }
                emailMessage.Body = alternative;

                using (var client = new SmtpClient())
                {
                    client.Connect(config.Host, config.Port);// SecureSocketOptions.None
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(config.UserName, config.Password);
                    client.Send(emailMessage);
                    client.Disconnect(true);
                }

                Console.WriteLine($"邮件发送成功！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"邮件发送失败：{ex.Message}");
                throw;
            }
        }
    }
}
